package com.cipe.cmrs.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.exception.InsecurePasswordException;
import com.cipe.cmrs.model.ActionableAlert;
import com.cipe.cmrs.model.ActionableAlertsMessage;
import com.cipe.cmrs.model.ChangeNotificationsMessage;
import com.cipe.cmrs.model.Changenotification;
import com.cipe.cmrs.model.DashBoardLink;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.model.UserPreference;
import com.cipe.cmrs.service.ActionableAlertMesageService;
import com.cipe.cmrs.service.ActionableAlertService;
import com.cipe.cmrs.service.ChangeNotificationMessageService;
import com.cipe.cmrs.service.ChnageNotificationService;
import com.cipe.cmrs.service.DashBoardService;
import com.cipe.cmrs.service.LinkCategoryService;
import com.cipe.cmrs.service.RegionService;
import com.cipe.cmrs.service.UserService;
import com.cipe.cmrs.service.ref.EntityRefService;
import com.cipe.cmrs.util.UserUtil;

@Controller
public class DashboardController extends BaseController {

	private static final long serialVersionUID = 2953245877386975346L;
	// REplace this with "dashboard2" to see the new ui
	private String formView = "dashboard";

	@Autowired
	private UserService userService;
	@Autowired
	private EntityRefService entityRefService;

	@Autowired
	private DashBoardService dashBoardService;

	@Autowired
	ActionableAlertMesageService actionableAlertService;

	@Autowired
	ChangeNotificationMessageService changeNotificationMessageService;

	@Autowired
	ActionableAlertService alertService;
	@Autowired
	ChnageNotificationService chnageNotificationService;
	@Autowired
    private LinkCategoryService linkCategoryService;
	
	@Autowired
	RegionService regionService;

	@RequestMapping("/secure/changePassword.do")
	public String changePassword(@ModelAttribute User user,
			BindingResult result, Model model, HttpServletRequest request) {
		try {
			userService.changePassword(user);
			saveMessage(request, getText("changePassword.message.success"));
		} catch (InsecurePasswordException e) {
			logger.error(getText("error.insecurePassword"), e);
			saveError(request, getText("error.insecurePassword"));
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}

		user.setPassword(null);
		user.setConfirmPassword(null);
		user.setNewPassword(null);
		model.addAttribute("user", user);
		return "changePassword";
	}

	@RequestMapping("/secure/manageAccountCodes.do")
	public String manageAccountCodes() {
		return "manageAccountCodes";
	}

	@RequestMapping("/secure/checkSession.do")
	public void checkSession(HttpServletRequest request,
			HttpServletResponse resp) throws IOException {
		// logger.debug("checkSession....");
		HttpSession session = request.getSession();
		if (session.getAttribute(User.LOGGED_IN_USER_KEY) != null) {
			resp.getWriter().write("success");
		} else {
			resp.getWriter().write("failed");
		}

	}

	@RequestMapping("/secure/manageFieldOffices.do")
	public String manageFieldOffices() {
		return "manageFieldOffices";
	}

	@RequestMapping("/secure/manageRegionCountriesAndStates.do")
	public String manageRegionCountriesAndStates() {
		return "manageRegionCountriesAndStates";
	}

	// @RequestMapping("/secure/addDonorAward.do")
	// public String addDonorAward() {
	// return "addDonorAward";
	// }
	@RequestMapping("/secure/manageUsersAndRoles.do")
	public String manageUsersAndRoles() {
		return "manageUsersAndRoles";
	}

	@RequestMapping("/secure/processPaymentReq.do")
	public String processPaymentReq() {
		return "processPaymentReq";
	}

	@RequestMapping("/secure/refreshDashboard.do")
	public String refreshDashboard(Model model, HttpServletRequest request) {
		modelAttributeRequiredForDashboard(request, model);
		return "dashboardDiv";
	}

    @RequestMapping(method = RequestMethod.POST, value = "/secure/actionalertFilterDashboard.do")
	public String actionalertFilterDashboard(
			@ModelAttribute UserPreference userPreference, Model model,
			HttpServletRequest request) {
		model.addAttribute("ActionableAlertList",
				actionableAlertService.getAllActionableAlert(userPreference));
		model.addAttribute("userPreference", userPreference);
		User user = UserUtil.INSTANCE.getCurrentUser();
		UserPreference oldUserPreference = user.getUserPreference();
		if (oldUserPreference == null) {
			oldUserPreference = new UserPreference();
		}
		oldUserPreference.setAaid(userPreference.getAaid());
		oldUserPreference.setAaDateid(userPreference.getAaDateid());
		oldUserPreference.setAaAsignId(userPreference.getAaAsignId());
		oldUserPreference.setAaReagionId(userPreference.getAaReagionId());
		/* userPreference.setUser(user); */
		user.setUserPreference(userPreference);
		userService.merge(user);
		model.addAttribute("regionList",regionService.findAllOrderBy("displayName") );
		model.addAttribute("user",user);
		return "actionableAlret";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/secure/changeNotificationFilterDashboard.do")
	public String changeNotificationFilterDashboard(
			@ModelAttribute UserPreference userPreference, Model model,
			HttpServletRequest request) {
		User user = UserUtil.INSTANCE.getCurrentUser();
		UserPreference oldUserPreference = user.getUserPreference();
		if (oldUserPreference == null) {
			oldUserPreference = new UserPreference();
		}
		oldUserPreference.setCnid(userPreference.getCnid());
		oldUserPreference.setCnDateid(userPreference.getCnDateid());
		oldUserPreference.setCnAsignId(userPreference.getCnAsignId());
		oldUserPreference.setCnReagionId(userPreference.getCnReagionId());
		/* userPreference.setUser(user); */
		user.setUserPreference(userPreference);
		userService.merge(user);
		model.addAttribute("ChangeNotificationList",
				changeNotificationMessageService.getAllChangeNotification(
						userPreference, user));
		model.addAttribute(userPreference);
		return "dashboardCN";
	}

	@RequestMapping("/secure/changeNotification.do")
	public String changeNotification(@RequestParam("id") int id, Model model,
			HttpServletRequest request) {
		User user = UserUtil.INSTANCE.getCurrentUser();
		changeNotificationMessageService.chnageNotificationPeference(user, id);
		userService.merge(user);
		UserPreference userPreference = user.getUserPreference();
		model.addAttribute("ChangeNotificationList",
				changeNotificationMessageService.getAllChangeNotification(
						userPreference, user));
		return "dashboardCN";
	}

	// @RequestMapping("/secure/donorAwardList.do")
	// public String donorAwardList() {
	// return "donorAwardList";
	// }
	// @RequestMapping("/secure/showAddProject.do")
	// public String showAddProject(){
	// return "editProject";
	// }
	//
	// @RequestMapping("/secure/showProjectList.do")
	// public String showProjectList() {
	// return "projectList";
	// }
	@RequestMapping("/secure/reportComputerProblem.do")
	public String reportComputerProblem() {
		return "reportComputerProblem";
	}

	// Partner Monitoring
	@RequestMapping("/secure/searchAudit.do")
	public String searchAudit() {
		return "searchAudit";
	}

	@RequestMapping("/secure/searchDonor.do")
	public String searchDonor() {
		return "searchDonor";
	}

	@RequestMapping("/secure/searchDonorAward.do")
	public String searchDonorAward() {
		return "searchDonorAward";
	}

	@RequestMapping("/secure/searchPartner.do")
	public String searchPartner() {
		return "searchPartner";
	}

	@RequestMapping("/secure/searchPaymentProcessing.do")
	public String searchPaymentProcessing() {
		return "searchPaymentProcessing";
	}

	@RequestMapping("/secure/searchProject.do")
	public String searchProject() {
		return "searchProject";
	}

	// // Payment Processing
	// @RequestMapping("/secure/showAddAudit.do")
	// public String showAddAudit() {
	// return "editAudits";
	// }

	@RequestMapping("/secure/showAddFinNarRepReq.do")
	public String showAddFinNarRepReq() {
		return "addFinNarRepReq";
	}

	@RequestMapping("/secure/showAddPartnerMonDetail.do")
	public String showAddPartnerMonDetail() {
		return "addPartnerMonDetail";
	}

	@RequestMapping("/secure/showAddPaymentProcessing.do")
	public String showAddPaymentProcessing() {
		return "editPaymentProcessing";
	}

	@RequestMapping("/secure/showAuditList.do")
	public String showAuditList() {
		return "auditList";
	}

	// Knowledge Management
	/*
	 * @RequestMapping("/secure/showAddKnowledgeManagement.do") public String
	 * showAddKnowledgeManagement(){ return "editKnowledgeManagement"; }
	 * 
	 * @RequestMapping("/secure/showKnowledgeManagementList.do") public String
	 * showKnowledgeManagementList() { return "knowledgeManagementList"; }
	 */
	// Reports
	@RequestMapping("/secure/showChangePassword.do")
	public String showChangePassword(HttpServletRequest request, Model model) {
		User loggedInUser = UserUtil.INSTANCE.getCurrentUser();
		User user = new User();
		user.setLoginName(loggedInUser.getLoginName());
		model.addAttribute("user", user);
		return "changePassword";
	}

	// Contact Us
	@RequestMapping("/secure/showEditFinNarRepReq.do")
	public String showEditFinNarRepReq() {
		return "editFinNarRepReq";
	}

	@RequestMapping("/secure/showEditPartnerMonDetail.do")
	public String showEditPartnerMonDetail() {
		return "editPartnerMonDetail";
	}

	@RequestMapping("/secure/showEmailGrantManagement.do")
	public String showEmailGrantManagement() {
		return "emailGrantManagement";
	}

	/**
	 * @author Krishna
	 * This Method add all the model attribute required for Dashboard and Home page.
	 * @param request
	 * @param model
	 */
	public void modelAttributeRequiredForDashboard(HttpServletRequest request,
			Model model) {
		User user = UserUtil.INSTANCE.getCurrentUser();
		UserPreference userPreference = user.getUserPreference();
		List<DashBoardLink> projectLinks = null;
		List<DashBoardLink> paymentsLinks = null;
		List<DashBoardLink> partnerLinks = null;
		List<DashBoardLink> donorLinks = null;

		/**
		 * The default value should be assigned to me Show the dash board links is not going to used further
		 * 
		 */
		if (userPreference == null) {
			/*boardLinks = dashBoardService.getAllDashboarBoardLinks();
			projectLinks = boardLinks.subList(0, 10);
			paymentsLinks = boardLinks.subList(10, 14);
			partnerLinks = boardLinks.subList(14, 26);
			donorLinks = boardLinks.subList(26, 28);*/
			userPreference=new UserPreference();
			userPreference.setPartnerAsignId(user.getId());
			userPreference.setProjectAsignId(user.getId());
			userPreference.setPaymentAssingId(user.getId());
			userPreference.setAaAsignId(user.getId());
			userPreference.setCnAsignId(user.getId());
			user.setUserPreference(userPreference);
			userService.merge(user);
		} 
			projectLinks = dashBoardService.getFilterDashboardLinks(
					"get_dashboard_filter_count",
					userPreference.getProjectAsignId(),
					userPreference.getProjectReagionId());
			paymentsLinks = dashBoardService.getPaymentLinks(
					"get_payment_request_count",
					userPreference.getPaymentAssingId());
			partnerLinks = dashBoardService.getFilterDashboardLinks(
					"get_PM_filter_count", userPreference.getPartnerAsignId(),
					userPreference.getPartnerReagionId());
			donorLinks=dashBoardService.getDonorLinks();

		model.addAttribute("projectLinks", projectLinks);
		model.addAttribute("paymentsLinks", paymentsLinks);
		model.addAttribute("partnerLinks", partnerLinks);
		model.addAttribute("donorLinks", donorLinks);

		model.addAttribute("user", user);
		model.addAttribute("regionList",regionService.findAllOrderBy("displayName") );
		model.addAttribute("userPreference",userPreference);
		List<ActionableAlert> actionableAlerts = alertService
				.getAllActionableAlert();
		model.addAttribute("actionableAlerts", actionableAlerts);
		/*ActionableAlert actionableAlert = new ActionableAlert();
		Changenotification changenotification = new Changenotification();
		if (userPreference != null) {
			actionableAlert.setId(userPreference.getAaid());
			actionableAlert.setDateid(userPreference.getAaDateid());
			changenotification.setId(userPreference.getCnid());
			changenotification.setDateid(userPreference.getCnDateid());
		}*/
		List<ActionableAlertsMessage> actionableAlertsMessages = actionableAlertService
				.getAllActionableAlert(userPreference);
		/*model.addAttribute("actionableAlert", actionableAlert);
		model.addAttribute("changenotification", changenotification);*/
		
		List<ChangeNotificationsMessage> changeNotificationsMessages = changeNotificationMessageService
				.getAllChangeNotification(userPreference, user);
		model.addAttribute("ActionableAlertList", actionableAlertsMessages);
		List<Changenotification> changenotifications = chnageNotificationService
				.getAllChangeNotification();
		model.addAttribute("changenotifications", changenotifications);
		model.addAttribute("ChangeNotificationList",
				changeNotificationsMessages);

	}

	@RequestMapping(method = RequestMethod.POST, value = "/secure/filterProject.do")
	public String filterProject(HttpServletRequest request,@ModelAttribute UserPreference preference, Model model) {
		User user = UserUtil.INSTANCE.getCurrentUser();
		UserPreference userPreference = user.getUserPreference();
		if (userPreference == null) {
			userPreference = new UserPreference();
		}
		userPreference.setProjectAsignId(preference.getProjectAsignId());
		userPreference.setProjectReagionId(preference.getProjectReagionId());
		/* userPreference.setUser(user); */
		user.setUserPreference(userPreference);
		userService.merge(user);
		List<DashBoardLink> projectLinks = dashBoardService.getFilterDashboardLinks(
				"get_dashboard_filter_count",
				userPreference.getProjectAsignId(),
				userPreference.getProjectReagionId());
		model.addAttribute("projectLinks", projectLinks);
	return "dashboardProject";
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/secure/filterPayment.do")
	public String filterPayment(HttpServletRequest request,@ModelAttribute UserPreference preference, Model model) {
		User user = UserUtil.INSTANCE.getCurrentUser();
		UserPreference userPreference = user.getUserPreference();
		if (userPreference == null) {
			userPreference = new UserPreference();
		}
		userPreference.setPaymentAssingId(preference.getPaymentAssingId());
		/* userPreference.setUser(user); */
		user.setUserPreference(userPreference);
		userService.merge(user);
		List<DashBoardLink> paymentsLinks = dashBoardService.getPaymentLinks(
				"get_payment_request_count",
				userPreference.getPaymentAssingId());
		model.addAttribute("paymentsLinks", paymentsLinks);
	return "dashboardPayment";
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/secure/filterPartner.do")
	public String filterPartner(HttpServletRequest request,@ModelAttribute UserPreference preference, Model model) {
		User user = UserUtil.INSTANCE.getCurrentUser();
		UserPreference userPreference = user.getUserPreference();
		if (userPreference == null) {
			userPreference = new UserPreference();
		}
		userPreference.setPartnerAsignId(preference.getPartnerAsignId());
		userPreference.setPartnerReagionId(preference.getPartnerReagionId());
		/* userPreference.setUser(user); */
		user.setUserPreference(userPreference);
		userService.merge(user);
		List<DashBoardLink> partnerLinks = dashBoardService.getFilterDashboardLinks(
				"get_PM_filter_count", userPreference.getPartnerAsignId(),
				userPreference.getPartnerReagionId());
		model.addAttribute("partnerLinks", partnerLinks);
	return "dashboardPartner";
	}

    @RequestMapping("/secure/showDashboard.do")
    public String showLogin(HttpServletRequest request, Model model) {
        model.addAttribute("user", UserUtil.INSTANCE.getCurrentUser());
        model.addAttribute("linkCategories", linkCategoryService.getAllAllowedLinks());
//        model.addAttribute("linkCategories", entityRefService.findAll(LinkCategory.class));
        modelAttributeRequiredForDashboard(request, model);
        return formView;
    }

	@RequestMapping("/secure/showPageHeading.do")
	public String showPageHeading(@RequestParam String heading, Model model) {
		model.addAttribute("heading", heading);
		return "headingPage";
	}

	@RequestMapping("/secure/showPartnerMonDetail.do")
	public String showPartnerMonDetail() {
		return "partnerMonDetail";
	}

	// Audit
	@RequestMapping("/secure/showPaymentProcessingList.do")
	public String showPaymentProcessingList() {
		return "paymentProcessingList";
	}

	@RequestMapping("/secure/showReportList.do")
	public String showReportList() {
		return "reportList";
	}

	@RequestMapping("/secure/systemReq.do")
	public String systemReg() {
		return "systemReg";
	}
}
